package com.kadron.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.Currency;
import com.kadron.entity.Price;

@AutoCreate
@BypassInterceptors
@Name("currencyDAO")
public class KCurrencyDAO extends KDAO<Currency> {

	private static final Log log = LogFactory.getLog(KCurrencyDAO.class);
	
	public Currency find(long currencyId) {
		EntityManager em = getEntityManager();
		try {			
			return (Currency) em.createQuery("SELECT e FROM Currency e WHERE e.id = :id")
			.setParameter("id", currencyId)
			.getSingleResult();
		} catch (NoResultException e) {
			log.debug("Not foount currency dith id = "+currencyId);
			return null;
		}
	}
	
	public Currency find(String code) {
		EntityManager em = getEntityManager();
		try {			
			return (Currency) em.createQuery("SELECT e FROM Currency e WHERE e.code = :code")
			.setParameter("code", code)
			.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Price> getPrices(long itemId) {
		EntityManager em = getEntityManager();
		try {			
			return em.createQuery("SELECT e FROM Price e WHERE e.item.id = :item_id ")
			.setParameter("item_id", itemId)
			.getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
